//
//  SecondViewController.swift
//  全国高等学校查询
//
//  Created by 高宇超 on 6/13/17.
//  Copyright © 2017 Yuchao. All rights reserved.
//

import UIKit
import Crashlytics
import SystemConfiguration

enum YColor {
    case red, green, orange
}

enum State {
    case normal, filtering, loading, loaded
}

enum SiteURL {
    case hotRank, classifyRank, html, page, province, classify, schtype, flag, keyword, sortBy, baike, baidu
}


class NormalVC: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var provincePicker: UIPickerView!
    @IBOutlet weak var classifyPicker: UIPickerView!
    @IBOutlet weak var schtypePicker: UIPickerView!
    @IBOutlet weak var flagPicker: UIPickerView!
    @IBOutlet weak var filterView: UIView!
    @IBOutlet weak var loadingLabel: UILabel!
    @IBOutlet weak var classifyRankLabel: UILabel!
    @IBOutlet weak var hotRankLabel: UILabel!
    @IBOutlet weak var dotOne: UILabel!
    @IBOutlet weak var dotTwo: UILabel!
    @IBOutlet weak var resetBtn: UIButton!
    @IBOutlet weak var cancelBtn: UIButton!
    @IBOutlet weak var notifyLabel: UILabel!
    @IBOutlet weak var flagLabel: UILabel!
    
    static var usingNotifyLabel = false

    let toastTimeInterval: TimeInterval = 2.2
    
    let webViewMain = UIWebView()
    let webViewBaike = UIWebView()
    var html = ""
    var preHtml = ""
    var loadMoreTrigger = false
    var didReload = false
    var searched = false
    var searchFromReset = false
    var searchText = ""
    var startOffsetY: CGFloat = 0
    var noMoreToLoad = false
    var canceled = false
    var schools = [String]()
    var pickers = [0, 0, 0, 0]
    
    var state: State = .normal
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Track view did load
        Answers.logCustomEvent(withName: "Normal College View Loaded", customAttributes: ["time": DateFormatter().string(from: Date()), "device": UIDevice.current.modelName])

        self.filterView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard(sender:))))
        self.filterView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(dismissKeyboard(sender:))))
      
//        self.notifyLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissNotifiTap(sender:))))
//        self.notifyLabel.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(dismissNotifiPan(sender:))))

        webViewMain.delegate = self
        webViewMain.tag = 0
        
        webViewBaike.delegate = self
        webViewBaike.tag = 1
        
        flagLabel.layer.cornerRadius = 3
        
        if searchBar.becomeFirstResponder() {
            searchBar.text = " "
        }
        
    }

    override func viewWillAppear(_ animated: Bool) {
        restoreAllAnis()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        removeAllAnis()
    }
        
    func hotRankPressed(sender: UISegmentedControl) {
        
    }
    
    func dismissNotifiTap(sender: UITapGestureRecognizer) {
        UIView.dismissNotify(label: notifyLabel)
    }
    
    func dismissNotifiPan(sender: UITapGestureRecognizer) {
        UIView.dismissNotify(label: notifyLabel)
    }
    
    
    // MARK :- WebView
    //
    func webViewDidStartLoad(_ webView: UIWebView) {
        switch webView.tag {
        case 0: // main
            printit(any: webView.stringByEvaluatingJavaScript(from: "document.readyState")!)
            if state != .loading && state != .loaded {
                showLoadingLabel()
                state = .loading
            }
            if state == .loaded {
                webView.stopLoading()
            }
        case 1: // baike
            break
        default:
            break
        }
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        switch webView.tag {
        case 0: // main
            if canceled { return }
            printit(any: "\(webView.isLoading) \(webView.stringByEvaluatingJavaScript(from: "document.readyState")!)")
            if !webView.isLoading {
                let webState = webView.stringByEvaluatingJavaScript(from: "document.readyState")!
                let schs = webView.rtrvSchools()
                if webState == "interactive" && schs.count == 0 {
                    webView.reload()
                    return
                }
                if !webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML")!.contains("140769") {
                    UIView.notifyc(label: notifyLabel, text: "网络连接似乎不正常呢", color: .orange, duration: 2.02)
                    hideLoadingLabel()
                    return
                }
                
                hideLoadingLabel()
                state = .loaded
                if schs.count == 0 && retrieveCurrentPage() == 1 {
                    // no schools for current index
                    schools = []
                    tableView.reloadData()
                    noMoreToLoad = true
                    // Toast here "没有结果！换个别的搜一搜~ 👀"
                    UIView.notifyc(label: notifyLabel, text: "没有结果！换个别的搜一搜~ 👀", color: .orange, duration: toastTimeInterval, id: 2)
                } else {
                    // show results
                    didReload = false
                    if searched {
                        schools = schs
                        searched = false
                        UIView.notifyc(label: notifyLabel, text: "加载完毕~ 😊", color: .green, duration: toastTimeInterval, id: 0)
                        tableView.reloadData()
                        tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
                    } else {
                        if schs.count == 0 {
                            // loaded all schools, no more to be loaded
                            noMoreToLoad = true
                            // Toast here "全部加载完毕！✌️"
                            UIView.notifyc(label: notifyLabel, text: "已经加载全部结果！✌️", color: .red, duration: toastTimeInterval, id: 1)
                        } else {
                            schools.append(contentsOf: schs)
                            let notifyText = preHtml == "" ? "小鹰自动加载了全部高校👻" : "加载完毕~ 😊"
                            UIView.notifyc(label: notifyLabel, text: notifyText, color: .green, duration: toastTimeInterval, id: 0)
                            tableView.reloadData()
                        }
                    }
                }
            }
        case 1: // baike
            break
        default:
            break
        }

    }
    
    func loadPage(page: Int = 1, flag: String = "", keyword: String = "", province: String = "", classify: String = "", schtype: String = "") -> Void {
        if connectedToNetwork() {
            state = .normal
            preHtml = html
            html = htmls[.html]!.appending(htmls[.page]!).appending(int: page).appending(htmls[.flag]!).appending(flag.components(separatedBy: .whitespaces).joined()).appending(htmls[.keyword]!).appending(keyword).appending(htmls[.province]!).appending(province).appending(htmls[.classify]!).appending(classify).appending(htmls[.schtype]!).appending(schtype).percentEncoding()
            guard let url = URL(string: html) else { return }
            let request = URLRequest(url: url)
            let req = webViewMain.request
            if req == nil || (req != nil && request != req!) {
                webViewMain.loadRequest(request)
            }
        } else {
            UIView.notifyc(label: notifyLabel, text: "没有网络..😣", color: .orange, duration: 2.02, delay: 0)
        }
    }
    
    func loadHTML(html: String, webView: UIWebView) -> Void {
        guard let url = URL(string: html.percentEncoding()) else { return }
        let request = URLRequest(url: url)
        webView.loadRequest(request)
    }
    
    func loadHTMLByCheckNetwork(html: String, webView: UIWebView) -> Bool {
        if connectedToNetwork() {
            loadHTML(html: html, webView: webView)
            return true
        } else {
            UIView.notifyc(label: notifyLabel, text: "没有网络..😣", color: .orange, duration: 2.02, delay: 0)
            return false
        }
    }
    
    @IBAction func resetBtnPressed(_ sender: Any) {
        if !searchFromReset {
            searchFromReset = true
            searchBar.becomeFirstResponder()
            searchBar.text = " "
        }
    }
    
    @IBAction func cancelBtnPressed(_ sender: Any) {
        canceled = true
        webViewMain.stopLoading()
        hideLoadingLabel()
        // page load problem
        html = preHtml
        searchBar.text = searchText
        searchFromReset = false
    }
    
    // MARK :- PickerView
    //
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 32
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let label = UILabel()
        label.font.withSize(14)
        label.textAlignment = .center
        label.minimumScaleFactor = 0.5
        label.adjustsFontSizeToFitWidth = true
        label.text = self.pickerView(pickerView, titleForRow: row, forComponent: component)
        return label
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        switch pickerView.tag {
        case 0:
            return row == 0 ? "全国" : provinceArr[row]
        case 1:
            return row == 0 ? "全部" : classifyArr[row]
        case 2:
            return row == 0 ? "全部" : schtypeArr[row]
        case 3:
            return row == 0 ? "全部" : flagArr[row]
        default:
            return ""
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if let text = searchBar.text {
            if text == "" {
                searchBar.text = " "
            }
        }
        switch pickerView.tag {
        case 0:
            break
        case 1:
            break
        case 2:
            break
        case 3:
            break
        default: break
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        switch pickerView.tag {
        case 0:
            return provinceArr.count
        case 1:
            return classifyArr.count
        case 2:
            return schtypeArr.count
        case 3:
            return flagArr.count
        default:
            return 0
        }
    }
    
    // MARK :- TableView
    //
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return schools.count
    }
    
    func retrieveCurrentPage() -> Int {
        return Int(html.components(separatedBy: htmls[.page]!)[1].components(separatedBy: htmls[.flag]!)[0])!
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "normalCell") as! NormalCell

        if indexPath.row == schools.count - 1 {
            loadMoreTrigger = true
        } else {
            // calculate if current position is the most bottom position
            let cellCount = Int(tableView.frame.height / cell.frame.height)
            loadMoreTrigger = loadMoreTrigger && indexPath.row + cellCount >= schools.count - 1
        }
        
        var info = schools[indexPath.row].components(separatedBy: CharacterSet(charactersIn: "\t"))
        if info.count > 4 {
            cell.name.text = (info[0].components(separatedBy: .decimalDigits) as Array).joined() // remove digits from name string
            cell.province.text = info[1]
            cell.schtype.text = info[2]
            cell.rankAll.text = info[3]
            cell.rankClass.text = info[4]
            setRoundCornerBgForCellLabel(label: cell.province, pickerRow: provincePicker.selectedRow(inComponent: 0))
            setRoundCornerBgForCellLabel(label: cell.rankClass, pickerRow: classifyPicker.selectedRow(inComponent: 0))
            setRoundCornerBgForCellLabel(label: cell.schtype, pickerRow: schtypePicker.selectedRow(inComponent: 0))
        } else {
            cell.removeFromSuperview()
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) as? NormalCell {
            let name = cell.name.text!
            guard let url = URL(string: htmls[.baike]!.appending(name).percentEncoding()) else { return }
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: {
                    success in
                    if success {
                        Answers.logCustomEvent(withName: "Jump to Baike", customAttributes: [
                            "name": name,
                            "searchText": self.searchText,
                            "province": provinceArr[self.provincePicker.selectedRow(inComponent: 0)],
                            "classify": classifyArr[self.classifyPicker.selectedRow(inComponent: 0)],
                            "schtype": schtypeArr[self.schtypePicker.selectedRow(inComponent: 0)],
                            "flag": flagArr[self.flagPicker.selectedRow(inComponent: 0)],
                            "device": UIDevice.current.modelName,
                            ])
                    }
                })
            } else {
                // Fallback on earlier versions
                UIApplication.shared.openURL(url)
            }
        }
    }
    
    // set the background of labels in table cell be gray and cut round corner if picked something
    func setRoundCornerBgForCellLabel(label: UILabel, pickerRow: Int) {
        label.layer.cornerRadius = 3
        label.backgroundColor = pickerRow > 0 ? UIColor(red: 0.922, green: 0.922, blue: 0.922, alpha: 1) : UIColor.clear
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        startOffsetY = scrollView.contentOffset.y
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if scrollView.contentOffset.y > scrollView.contentSize.height - scrollView.frame.size.height {
            if scrollView.contentOffset.y > startOffsetY {
                if loadMoreTrigger && !noMoreToLoad && !webViewMain.isLoading {
                    UIView.dismissNotify(label: notifyLabel)
                    loadPage(page: retrieveCurrentPage() + 1,
                             flag: flagArr[flagPicker.selectedRow(inComponent: 0)],
                             keyword: searchText,
                             province: provinceArr[provincePicker.selectedRow(inComponent: 0)],
                             classify: classifyArr[classifyPicker.selectedRow(inComponent: 0)],
                             schtype: schtypeArr[schtypePicker.selectedRow(inComponent: 0)])
                } else if noMoreToLoad {
                    // Toast here "已经是全部了！🙄"
                    UIView.notifyc(label: notifyLabel, text: "已经是全部了！🙄", color: .red, duration: toastTimeInterval, id: 3)
                }
            }
        }
    }
    
    // MARK :- SearchBar
    //
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.text = searchText
        showFilterView()
        // save the states of pickerviews in case user canceled search
        pickers[0] = provincePicker.selectedRow(inComponent: 0)
        pickers[1] = classifyPicker.selectedRow(inComponent: 0)
        pickers[2] = schtypePicker.selectedRow(inComponent: 0)
        pickers[3] = flagPicker.selectedRow(inComponent: 0)
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        hideFilterView()
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        let text = searchBar.text
        if text == "" || text == nil {
            searchBar.text = " "
        }
    }
    
    // canceled
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        // set the pickerviews to old states if canceled
        dismissKeyboard(sender: UISegmentedControl())
    }
    
    // searched
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        let row = flagPicker.selectedRow(inComponent: 0)
        if row > 0 {
            flagLabel.text = flagArr[row]
            flagLabel.sizeToFit()
            flagLabel.frame.size.height = 20
            flagLabel.frame.size.width += 10
            flagLabel.frame.origin = CGPoint(x: 22, y: 12)
        } else {
            flagLabel.text = ""
            flagLabel.sizeToFit()
        }
        
        let text = searchBar.text!
        let flag = flagArr[flagPicker.selectedRow(inComponent: 0)]
        let province = provinceArr[provincePicker.selectedRow(inComponent: 0)]
        let classify = classifyArr[classifyPicker.selectedRow(inComponent: 0)]
        let schtype = schtypeArr[schtypePicker.selectedRow(inComponent: 0)]

        // fabric record
        Answers.logCustomEvent(withName: "Normal Searched", customAttributes: ["searchText": searchBar.text!, "flag": flag, "province": province, "classify": classify, "schtype": schtype, "device": UIDevice.current.modelName])
        
        searchText = text.removeSpaces()
        searched = true
        noMoreToLoad = false
        dismissSearchBar()
        loadPage(flag: flag,
                 keyword: searchText,
                 province: province,
                 classify: classify,
                 schtype: schtype)
    }
    
    func dismissSearchBar() -> Void {
        searchBar.text = searchText
        searchFromReset = false
        searchBar.resignFirstResponder()
        if webViewMain.request == nil { loadPage() }
    }
    
    func dismissKeyboard(sender: UISegmentedControl) {
        dismissSearchBar()
        provincePicker.selectRow(pickers[0], inComponent: 0, animated: false)
        classifyPicker.selectRow(pickers[1], inComponent: 0, animated: false)
        schtypePicker.selectRow(pickers[2], inComponent: 0, animated: false)
        flagPicker.selectRow(pickers[3], inComponent: 0, animated: false)
    }
    
    // MARK :- Animations
    //
    func showLoadingLabel() {
        if self.searchBar.resignFirstResponder() { self.searchBar.text = "" }
        self.resetBtn.isEnabled = false
        self.dotOne.frame.origin.x = self.loadingLabel.frame.origin.x + 58
        self.dotTwo.frame.origin.x = self.loadingLabel.frame.origin.x + 64
        UIView.animate(withDuration: 0.24, delay: 0, options: [.curveEaseInOut], animations: {
            self.searchBar.frame.origin.y = -24
            self.searchBar.alpha = 0
            self.resetBtn.alpha = 0
            self.flagLabel.alpha = 0
            self.hotRankLabel.alpha = 0
            self.classifyRankLabel.alpha = 0
            self.view.layoutIfNeeded()
        }, completion: {
            finished in
            if finished {
                // show cancel button
                UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: {
                    self.cancelBtn.alpha = 1
                }, completion: {
                    finished in
                    if finished {
                        if self.state != .loading {
                            self.cancelBtn.alpha = 0
                        } else {
                            self.cancelBtn.isEnabled = true
                        }
                    }
                })
            }
        })
        DispatchQueue.global(qos: .userInitiated).async {
            DispatchQueue.main.async { self.repeatLoadingDots() }
        }
    }
    
    func hideLoadingLabel() {
        resetLoadingState()
        UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: {
            self.searchBar.frame.origin.y = 20
            self.searchBar.alpha = 1
            self.resetBtn.alpha = 1
            self.flagLabel.alpha = 1
            self.hotRankLabel.alpha = 1
            self.classifyRankLabel.alpha = 1
            self.cancelBtn.alpha = 0
            self.view.layoutIfNeeded()
        }, completion: {
            finished in
            if finished {
                self.resetBtn.isEnabled = true
                self.canceled = false
            }
        })
    }

    func resetLoadingState() {
        self.state = .normal
        self.cancelBtn.isEnabled = false
        self.cancelBtn.layer.removeAllAnimations()
        self.dotOne.layer.removeAllAnimations()
        self.dotTwo.layer.removeAllAnimations()
        self.dotOne.alpha = 1
        self.dotTwo.alpha = 1
        self.dotOne.frame.origin.x = self.loadingLabel.frame.origin.x + 58
        self.dotTwo.frame.origin.x = self.loadingLabel.frame.origin.x + 64
        self.view.layoutIfNeeded()
    }
    
    func repeatLoadingDots() {
        UIView.animate(withDuration: 0.5, delay: 0, options: [.curveEaseInOut], animations: {
            self.dotOne.frame.origin.x -= 3
            self.dotOne.alpha = 0
            self.dotTwo.frame.origin.x -= 6
            self.dotTwo.alpha = 0
            self.view.layoutIfNeeded()
        }, completion: {
            finished in
            if finished {
                UIView.animate(withDuration: 0.5, delay: 0, options: [.curveEaseInOut], animations: {
                    self.dotOne.frame.origin.x += 3
                    self.dotOne.alpha = 1
                    self.dotTwo.frame.origin.x += 3
                    self.view.layoutIfNeeded()
                }, completion: {
                    finished in
                    if finished {
                        UIView.animate(withDuration: 0.5, delay: 0, animations: {
                            self.dotTwo.frame.origin.x += 3
                            self.dotTwo.alpha = 1
                            self.view.layoutIfNeeded()
                        }, completion: {
                            finished in
                            if finished {
                                self.repeatLoadingDots()
                            }
                        })
                    }
                })
            }
        })
    }
    
    func showFilterView() {
        if state != .filtering {
            self.state = .filtering
            self.resetBtn.isEnabled = false
            self.filterView.layer.removeAllAnimations()
            UIView.animate(withDuration: 0.32, delay: 0, options: [.curveEaseInOut], animations: {
                self.filterView.frame.size.height = self.tableView.frame.size.height + 41
                self.view.layoutIfNeeded()
            }, completion: {
                finished in
                if finished {
                    UIView.animate(withDuration: 0.21, animations: {
                        self.setAlphaToPickers()
                    }, completion: {
                        finished in
                        if finished {
                            if self.state != .filtering {
                                self.filterView.frame.size.height = 41
                                return 
                            }
                            self.filterView.isUserInteractionEnabled = true
                            if self.searchFromReset {
                                self.provincePicker.selectRow(0, inComponent: 0, animated: true)
                                self.classifyPicker.selectRow(0, inComponent: 0, animated: true)
                                self.schtypePicker.selectRow(0, inComponent: 0, animated: true)
                                self.flagPicker.selectRow(0, inComponent: 0, animated: true)
                            }
                        } else {
                            // no finished but do nothing
                        }
                    })
                } else {
                    // no finished but do nothing
                }
            })
        }
    }
    
    func hideFilterView() {
        if self.state == .filtering {
            self.filterView.isUserInteractionEnabled = false
            self.state = .normal
            self.filterView.layer.removeAllAnimations()
            UIView.animate(withDuration: 0.21, delay: 0, options: [.curveEaseInOut], animations: {
                self.setAlphaToPickers(a: 0)
            }, completion: {
                finished in
                UIView.animate(withDuration: 0.21, delay: 0, options: [.curveEaseInOut], animations: {
                    self.filterView.frame.size.height = 41
                    self.view.layoutIfNeeded()
                }, completion: {
                    finished in
                    if finished {
                        self.resetBtn.isEnabled = true
                    }
                })
            })
        }
    }
    
    func setAlphaToPickers(a: CGFloat = 1) {
        self.resetBtn.alpha = 1 - a
        self.flagLabel.alpha = 1 - a
        self.hotRankLabel.alpha = 1 - a
        self.classifyRankLabel.alpha = 1 - a
        self.provincePicker.alpha = a
        self.classifyPicker.alpha = a
        self.schtypePicker.alpha = a
        self.flagPicker.alpha = a
    }

    func restoreLoadingAni() {
        if state == .loading { showLoadingLabel() }
    }

    func removeAllAnis() {
        switch state {
        case .loading:
            dotOne.layer.removeAllAnimations()
            dotTwo.layer.removeAllAnimations()
        case .normal:
            resetBtn.layer.removeAllAnimations()
        case .filtering:
            resetBtn.layer.removeAllAnimations()
        case .loaded:
            resetBtn.layer.removeAllAnimations()
        }
        notifyLabel.layer.removeAllAnimations()
    }
    
    func restoreAllAnis() {
        switch state {
        case .loading:
            restoreLoadingAni()
        case .normal:
            resetBtn.show(duration: 0.17)
        case .loaded:
            resetBtn.show(duration: 0.17)
        case .filtering:
            resetBtn.hide(duration: 0.17)
        }
        UIView.dismissNotify(label: notifyLabel, delay: 0, id: -1)
    }
    

    // check if is connected to the network
    func connectedToNetwork() -> Bool {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
        zeroAddress.sin_family = sa_family_t(AF_INET)
        
        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                SCNetworkReachabilityCreateWithAddress(nil, $0)
            }
        }) else {
            return false
        }
        
        var flags: SCNetworkReachabilityFlags = []
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
            return false
        }
        
        let isReachable = flags.contains(.reachable)
        let needsConnection = flags.contains(.connectionRequired)
        
        return (isReachable && !needsConnection)
    }
}

func printit(any: Any) {
    print()
    print("----------------------------------------")
    print(any)
    print("----------------------------------------")
}

/*
 * toast id
 * 0 - loading completed
 * 1 - loaded all
 * 2 - no result for current index
 * 3 - already loaded all
 * 4 -
 */
let colors = [
    YColor.green: UIColor(red: 16 / 255, green: 206 / 255, blue: 105 / 255, alpha: 1),
    YColor.red: UIColor(red: 255 / 255, green: 36 / 255, blue: 40 / 255, alpha: 1),
    YColor.orange: UIColor(red: 255 / 255, green: 128 / 255, blue: 0, alpha: 1)
]

private let htmls: [SiteURL: String] = [
    .baidu: "https://www.baidu.com/s?wd=",
    .baike: "http://baike.baidu.com/item/",
    .html: "http://gkcx.eol.cn/soudaxue/queryschool.html?",
    .page: "&page=",
    .province: "&province=",
    .classify: "&recomschprop=",
    .schtype: "&argschtype=",
    .flag: "&schoolflag=",
    .keyword: "&keyWord1="
]

private let rankHtml: [SiteURL: String] = [
    .hotRank: "http://gkcx.eol.cn/schoolhtm/schoolTop100/monthly_0_0.htm",
    .classifyRank: "http://gkcx.eol.cn/sphtm/1/click_spIntro_top100.htm",
    .html: "http://gkcx.eol.cn/soudaxue/queryschool.html?",
    .page: "&page=",
    .province: "&province=",
    .classify: "&recomschprop=",
    .schtype: "&argschtype=",
    .flag: "&schoolflag=",
    .keyword: "&keyWord1="
]

private let provinceArr = ["", "北京", "天津", "河北", "河南", "山东", "山西", "陕西", "内蒙古", "辽宁", "吉林", "黑龙江", "上海", "江苏", "安徽", "江西", "湖北", "湖南", "重庆", "四川", "贵州", "云南", "广东", "广西", "福建", "甘肃", "宁夏", "新疆", "西藏", "海南", "浙江", "青海", "香港", "澳门"]
private let classifyArr = ["", "综合", "理工", "农业", "医药", "师范", "语言", "财经", "政法", "体育", "艺术", "民族", "军事", "其他"]
private let schtypeArr = ["", "普通本科", "独立学院", "高职高专", "中外合作办学", "远程教育学院", "HND 项目", "成人教育", "其他"]
private let flagArr = ["", "985 工程", "211 工程", "教育部直属", "中央部委", "自主招生试点"]


private let _404 = [
    "",
    ""
]

